﻿using Core.DataAccess.Model;
using Core.Framework;
using Dapper;
using iTool.ClusterComponent;
using Microsoft.AspNetCore.NodeServices;
using Orleans.Streams;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;

namespace iTool.Connector
{
    public class SubscribeStreamProvider : SubscribeQueueHandler<string>
    {
        public event EventHandler<KeyValuePair<string, string>> Handler;
        public SubscribeStreamProvider(string topic) : base(topic, AppSetting.QueueServiceStreamNamespace)
        {

        }

        public override Task OnErrorAsync(Exception ex)
        {
            return Task.CompletedTask;
        }

        public override Task OnMessageAsync(string message, StreamSequenceToken token)
        {
            try
            {
                this.Handler.Invoke(this, message.TryToEntity<KeyValuePair<string, string>>());
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            return Task.CompletedTask;
        }
    }

    public class AppSettingBuilder
    {
        private readonly IDBFactory iDBFactory;
        private readonly SubscribeStreamProvider subscribeStreamProvider;
        public AppSettingBuilder(IDBFactory iDBFactory) 
        {
            this.iDBFactory = iDBFactory;
            this.subscribeStreamProvider = new SubscribeStreamProvider(AppSetting.ScriptBudilerTopic);

            this.subscribeStreamProvider.Handler += (sender, message) => 
            {
                // 模块名称
                var moduleName = message.Key.Replace("./CloudFunctions/", "");

                if ("AppSetting" == moduleName)
                {
                    this.GetConfigValue(message.Value);
                }
            };

            this.subscribeStreamProvider.StartAsync().Wait();
        }


        private void GetConfigValue(string scriptContent)
        {
            scriptContent = scriptContent.Replace("module.exports =", "").Replace("module.exports=", "");
            File.WriteAllText("appsettings.json", scriptContent.TryToJObject().TryToJson());
        }

        public void Ini()
        {
            using (var db = iDBFactory.Create(DatabaseType.Function))
            {
                var func = db.Query<Function>("SELECT [scriptContent] FROM [Function] WHERE  MODULENAME = 'AppSetting'").FirstOrDefault();
                this.GetConfigValue(func?.scriptContent ?? "{}");
            }
        }
    }
}
